<template>
  <div class="search">
    <div class="search1">
      <van-search
        left=""
        v-model="value"
        shape="round"
        background="#1989fa"
        placeholder="请输入搜索关键词"
        @input="input"
        class="searchbox"
        ref="search"
        @search="search"
      >
        <template #left>
          <van-icon name="arrow-left" @touchstart.stop="btn" />
        </template>
      </van-search>
      <div class="wraper" v-if="searchlists.length == 0 || value == ''">
        <van-cell title="搜索历史" class="searchofhistory">
          <template #right-icon>
            <van-icon
              name="delete"
              class="delete"
              @touchstart="deletehistory"
            />
          </template>
        </van-cell>
        <div class="clickedwra">
          <span
            @click.stop="clicksearch(item.content)"
            class="clickedkeyitem"
            @touchstart="touchstartfn(index)"
            @touchmove="touchmovefn"
            @touchend="touchendfn"
            @contextmenu.prevent
            @selectstart.prevent
            v-for="(item, index) in searchOfhistory"
            :key="index"
            >{{ item.content }}</span
          >
        </div>
      </div>
      <ul v-else>
        <li
          class="item"
          v-for="(item, index) in searchlists"
          :key="index"
          @click="search(item)"
          v-html="highlightfn(item)"
        ></li>
      </ul>
    </div>
    <van-dialog
      v-model="show"
      @confirm="confirm"
      title="确认删除全部历史记录吗?"
      show-cancel-button
    >
    </van-dialog>
  </div>
</template>

<script>
import { searchkey } from '../../api/search'
import searchresults from './searchresults.vue'
import { mapState } from 'vuex'
import { Dialog } from 'vant'
export default {
  // 组件名称
  name: 'search',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 局部注册的组件
  components: { searchresults },
  // 组件状态值
  data () {
    return {
      value: '',
      searchlists: [],
      timer: null,
      isShow: false,
      results: [],
      msg: '',
      show: false
    }
  },
  watch: {
    // 监听当前正在活跃的路由,如果不是/search1搜索页面,就清空输入框的内容,下次进来就不会显示之前未清空的内容
    $route () {
      if (this.$route.path !== '/search1') {
        this.value = ''
      }
    }
  },
  methods: {
    // 长按删除某一条历史记录
    touchstartfn (i) {
      this.timer = setTimeout(() => {
        Dialog.confirm({
          message: '确认删除此条历史记录吗?',
        })
          .then(() => {
            this.$store.commit('deleteonesearchOfhistory', i)
          })
          .catch(() => {
            // on cancel
          });
      }, 1000)
    },
    // 如果在一秒钟之内用户手指移动了,可能是不想删除,就移除计时器
    touchmovefn () {
      clearTimeout(this.timer)
    },
    // 如果在一秒钟之内用户手指抬起了,可能是不想删除,就移除计时器
    touchendfn () {
      clearTimeout(this.timer)
    },
    // 回车进入搜索列表页面
    search () {
      this.$router.push('/searchresults/' + this.value)
    },
    // 点击回到主页
    btn () {
      this.$router.push('/layout/home')
    },
    // 输入关键字联想结果
    input () {
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (this.value !== '') {
          const res = await searchkey(this.value)
          this.searchlists = res.data.data.options
        } else {
          this.searchlists = []
        }
      }, 400)
    },
    // 正则替换关键词,高亮显示
    highlightfn (str) {
      const reg = new RegExp(this.value, 'ig')
      return str.replace(reg, match => {
        return `<span style="color:red">${match}</span>`
      })
    },
    // 点击搜索结果获取
    async search (content) {
      this.msg = content
      this.$store.commit('setsearchOfhistory', { content })
      this.$router.push('/searchresults/' + content)
    },
    // 点击搜索历史进入搜索列表
    clicksearch (content) {
      this.$router.push('/searchresults/' + content)
    },
    // 显示提示用户的确认删除历史记录弹出框
    deletehistory () {
      this.show = true
    },
    // 删除搜索历史记录功能
    confirm () {
      this.$store.commit('deletesearchOfhistory')
    }
  },
  computed: {
    ...mapState(['searchOfhistory'])
  },
  activated () {
    // 进入搜索页面后输入框获得焦点
    // 定时器可以解决输入框无法自动获取焦点问题
    setTimeout(() => {
      this.$refs.search.querySelector('input').focus()
    }, 200)
  }
}
</script>
<style scoped lang="less">
.searchbox {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}
.van-icon-arrow-left {
  color: #fff;
  font-size: 22px;
  margin-right: 10px;
}
.item {
  color: #000;
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #eee;
  padding: 0 20px;
  font-size: 14px;
}
.searchbox {
  height: 46px;
}
.delete {
  margin-top: 5px;
  font-size: 16px;
}
.searchofhistory {
  border-bottom: 1px solid #eee;
  padding-left: 0px;
  padding-right: 0px;
}
.wraper {
  padding: 0 15px;
}
.search {
  padding-top: 46px;
}
.clickedkeyitem {
  margin-right: 16px;
  margin-bottom: 10px;
  padding: 6px 16px;
  background-color: #eee;
  border-radius: 10px;
  color: #000;
  font-size: 14px;
}
.clickedwra {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
}
</style>
